import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../../large_data/pic/morphology'
img_name = 'i.png'
img_path1 = os.path.join(img_dir, img_name)

spr = 2
spc = 3
spn = 0
plt.figure(figsize=[12, 6])

sep('load')
img = cv.imread(img_path1, cv.IMREAD_COLOR)
print('original shape', img.shape)
my_show_img(img, 'original', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('erosion')
erosion = cv.erode(img, np.ones((5, 5), np.uint8), iterations=1)
my_show_img(erosion, 'erosion', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('dilation')
dilation = cv.dilate(img, np.ones((5, 5), np.uint8), iterations=1)
my_show_img(dilation, 'dilation', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('morpological gradient')
mgrad = cv.morphologyEx(img, cv.MORPH_GRADIENT, np.ones((5, 5), np.uint8))
my_show_img(mgrad, 'mgrad', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('dilation - erosion')
diff = cv.subtract(dilation, erosion)
my_show_img(diff, 'dilation - erosion', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))
